package com.zty.controller;

import com.zty.BO.ServerInfo;
import com.zty.DTO.ServerInfoDTO;
import com.zty.response.CommonResponse;
import com.zty.service.DiscoveryService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * @Author ZTY
 * @Description 注册中心服务
 * @Date 10:20 2023-12-23
 **/

@Validated
@RestController
@RequestMapping("/")
public class DiscoveryController {

    private final DiscoveryService discoveryService;

    //  使用构造器注入
    public DiscoveryController(DiscoveryService discoveryService) {
        this.discoveryService = discoveryService;
    }

    /**
     * 服务注册
     * @return
     */
    @PostMapping("/register")
    public CommonResponse<?> register(@RequestBody @Valid ServerInfoDTO serverInfo){
        discoveryService.register(serverInfo);
        return CommonResponse.success();
    }

    /**
     * 服务器给Meta发送心跳
     * @return
     */
    @PutMapping("/heartbeat")
    public void heartbeat(@RequestBody @Valid ServerInfoDTO serverInfo){
        discoveryService.heartbeat(serverInfo);
    }

    /**
     * 获取已注册服务的相关信息
     * @return
     */
    @GetMapping("services")
    public CommonResponse<?> services(){
        Map<String, List<ServerInfo>> map = discoveryService.services();
        return CommonResponse.success(map);
    }
}
